package mwt.xml.xdbforms.dblayer.query.impl;

import java.sql.ParameterMetaData;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import mwt.xml.xdbforms.dblayer.query.SQLOperation;
import mwt.xml.xdbforms.dblayer.query.QueryParameterBuilder;

/**
 * Questa classe implementa un builder concreto
 * per la costruzione di un PreparedStatement
 * @author Gianfranco Murador
 */
public class JDBCQueryParameterBuilder extends QueryParameterBuilder {

    private SQLOperation operation;

    public JDBCQueryParameterBuilder(SQLOperation operation) {
        this.operation = operation;
    }

    public SQLOperation getOperation() {
        return operation;
    }

    @Override
    public ParameterMetaData getParameterMetaData() {
        try {
            return preparedStatement.getParameterMetaData();
        } catch (SQLException ex) {
            Logger.getLogger(JDBCQueryParameterBuilder.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    @Override
    public void initializeStatement() {
        try {
            // operation.compile();
            System.out.println("OPERATION :" + operation.toString());
            preparedStatement = connection.prepareStatement(operation.toString());
        } catch (SQLException ex) {
            Logger.getLogger(JDBCQueryParameterBuilder.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void addParameterValue(int parameterIndex, Object x) throws SQLException {

        if (x instanceof Integer) {

            System.out.println("Il parametro e' un intero");

            preparedStatement.setInt(parameterIndex, (Integer) x);
        } else {

            System.out.println("Viene trattato come un'oggetto");

            preparedStatement.setObject(parameterIndex, x);
        }
    }
}

